﻿jQuery.fn.loadTable = function(options)
{
    function nvl(target, alt) {  if (target)	return target;	else	return alt;	    }
    function drawTable(jdata)
    {
        if (jdata != null)
        {
            if (typeof (jdata) == "string")
                jdata = eval(jdata);

            if (settings.columns == null || settings.columns.length == 0)
            {
                settings.columns = [];
                var map = {};
                jQuery.each(jdata, function(i, row)  {   jQuery.each(row, function(key, val){ map[key] = 1;  });  });
                jQuery.each(map, function(key, val)  {   settings.columns = settings.columns.concat(key);    });
            }

           jQuery.each(settings.columns, function(i, val) { if (settings.headings[val]==null) settings.headings[val] = val; });

            var thead = "";
            var tbody = "";
            jQuery.each(settings.columns, function(i, col) { thead = thead + "<th>" + settings.headings[col] + "</th>"; });
            jQuery.each(jdata, function(i, row)
            {
                tbody = tbody + "<tr>";
                jQuery.each(settings.columns, function(i, heading) { tbody = tbody + "<td>" + nvl(row[heading],"&nbsp;") + "</td>"; });
                tbody = tbody + "</tr>\n\r";
            }
                );
            thead = "<thead><tr>" + thead + "</tr></thead>";

            return (thead + tbody);
        }
    }

    var settings = jQuery.extend(
    {
        url: null,
        parameters: null,
        data: null,
        completed: null,
        columns: null, // ['C', 'B', 'A'],
        headings: { }
    }, options || {});

    if (settings.data == null)
    {
        var that = this;
        if (settings.url == null) return this;
        jQuery.getJSON(settings.url, settings.parameters, function(response)
        {
            that.html(drawTable(response));
            if (settings.completed)
                settings.completed.call(that);
        });
    }
    else
    {
        this.html(drawTable(settings.data));
        if (settings.completed)
            settings.completed(this);

    }
    return this;
};
